﻿using System.Configuration;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using AutoAOIProgram.Merge;
using AutoAOIProgram.Property;
using AutoAOIProgram.utils;
using OfficeOpenXml;

namespace AutoAOIProgram
{
    class  Program
    {
        
        
        private static readonly string aoiFilePath = ConfigurationManager.AppSettings["aoiFilePath"]!;
        private static readonly string aoiFilePath1 = ConfigurationManager.AppSettings["aoiFilePath1"]!;
        private static readonly string mapBakPath = ConfigurationManager.AppSettings["mapBakPath"]!;
        private static readonly string colorMapBakPath = ConfigurationManager.AppSettings["colorMapBakPath"]!;

        
        
        static async Task  Main(string[] args)
        {
            try
            {
                // 去找哪些客户 device 需要aoi合图
                List<AoiInfo> aoiInfoList = QueryUtils.AoiQuery();

                foreach (AoiInfo aoiInfo in aoiInfoList)
                {
                    Console.WriteLine(aoiInfo.custCode!);
                    Console.WriteLine(aoiInfo.device!);
                    LogHelper.Info(aoiInfo.custCode!);
                    LogHelper.Info(aoiInfo.device!);
                   
                    
                    // if(aoiInfo.custCode!="XYX") continue;
                    // if(aoiInfo.device != "SUN02GFG7Q") continue; 
                    
                    // 这里continue的只是暂时合图的
                    if (aoiInfo.custCode == "ZJL" || aoiInfo.custCode == "HWG" || aoiInfo.custCode == "TOL" 
                        || aoiInfo.custCode == "SBW" || aoiInfo.custCode == "GIN"  || aoiInfo.custCode == "TST"
                        || aoiInfo.custCode == "RPS") 
                    {
                        continue;
                    }

                    
                    // 先去找该客户下有哪些wafetlot在merge站点
                    List<TestInfo> testInfos = QueryUtils.AoiMergeWaferLotQuery(aoiInfo.custCode!,aoiInfo.device!);


                    if (testInfos.Count > 0)
                    {
                        LogHelper.Info($"共有 {testInfos.Count} 个 LOT 在 merge 站点： " +
                                       string.Join("; ", testInfos.Select(t => t.ToString())));
                    }
                    else
                    {
                        LogHelper.Info("当前没有 LOT 在 merge 站点。");
                        continue;
                    }
                    

                    foreach (TestInfo testInfo in testInfos)
                    {
                        LogHelper.Info("===========普通合图开始===========");
                        // if (testInfo.HEAD_LOT_ID != "FLMT10033.1") continue;
                        // SBW ALG 只要dpat。不需要合图,XYX 是复合芯片合图
                        if (aoiInfo.custCode == "SBW" || aoiInfo.custCode == "ALG" || aoiInfo.custCode == "XYX") continue; 
                        Console.WriteLine($"当前循环wflot{testInfo.WF_LOT} -- 片号{testInfo.WF_NO}--{testInfo.CP_NO}--{testInfo.RP_NO}");
                        LogHelper.Info($"当前循环wflot{testInfo.WF_LOT} -- 片号{testInfo.WF_NO}--{testInfo.CP_NO}--{testInfo.RP_NO}");
                        
                        testInfo.WF_LOT = Regex.Replace(testInfo.WF_LOT!, @"[\u202D\u200E\u200F\u202C\u202E]", "");
                        
                            
                        // 最后输出tmb的结果
                        StringBuilder tmbResult = new StringBuilder();
                        
                        // 最后输出tma的结果
                        StringBuilder tmaResult = new StringBuilder();
                        
                        
                        // 最后输出txt的结果
                        StringBuilder txtResult = new StringBuilder();
                        
                        StringBuilder lksTxtResult = new StringBuilder();
                        
                        
                        
                        if (String.IsNullOrEmpty(testInfo.WF_ID) || String.IsNullOrEmpty(testInfo.WF_LOT) ||
                        String.IsNullOrEmpty(testInfo.CP_NO) || String.IsNullOrEmpty(testInfo.RP_NO) || 
                        String.IsNullOrEmpty(testInfo.SERIAL_NO))
                        {
                            continue;
                        }
                        
                        int wfNo = Convert.ToInt32(testInfo.WF_NO);
                        
                        bool isAoIink = QueryUtils.QueryIsAoIink(aoiInfo.device!,testInfo.WF_LOT,wfNo.ToString(),aoiInfo.custCode!);

                        if (isAoIink)
                        {
                            LogHelper.Info($"当前循环wflot{testInfo.WF_LOT} -- 片号{testInfo.WF_NO}--{testInfo.CP_NO}--{testInfo.RP_NO} AOI已经合过图了！！");
                            Console.WriteLine($"当前循环wflot{testInfo.WF_LOT} -- 片号{testInfo.WF_NO}--{testInfo.CP_NO}--{testInfo.RP_NO} AOI已经合过图了！！");
                            continue;
                        }


                        if (aoiInfo.device == "MX08A_1B_CP_HA_DR" || aoiInfo.device == "MX06B_1C_CP_A_DR" ||
                            aoiInfo.device == "MX24A_1F_CP_A_DR" || aoiInfo.device == "MX24A_1D_CP_A_DR")
                        {
                             using HttpClient client = new HttpClient();
                            string dpatApi =
                                $"http://10.0.3.213:9110/api/StdfRetrieve/STDF_DPAT_General?LotID={testInfo.HEAD_LOT_ID}&Wfno={testInfo.WF_NO}";

                            try
                            {
                                HttpResponseMessage response = await client.GetAsync(dpatApi);

                                response.EnsureSuccessStatusCode();
                                string responseBody = await response.Content.ReadAsStringAsync();
                                LogHelper.Info(responseBody);

                            }
                            catch (HttpRequestException e)
                            {

                                List<string> mailReceiver = StringUtils.GetMailReceiver();
                                string subject = "dpat出现错误";
                                LogHelper.Error(subject);
                                MailHelper.SendMail(subject, e.Message, mailReceiver);
                            }
                        }
                        


                        bool isStep = QueryUtils.QueryIsStep(testInfo.HEAD_LOT_ID!, wfNo, testInfo.CP_NO,
                            testInfo.RP_NO);

                        
                        List<string> mailReceiverPe = StringUtils.GetMailReceiver();   
                        
                        if (isStep == false)
                        {
                            LogHelper.Error($"当前循环wflot{testInfo.WF_LOT} -- 片号{testInfo.WF_NO}--{testInfo.CP_NO}--{testInfo.RP_NO} 的map还没有生成");
                            string stepSubject = "合图失败";
                            string stepContent = $"该{testInfo.HEAD_LOT_ID!}，{testInfo.CP_NO}，{testInfo.RP_NO}，{testInfo.WF_NO}片，map还没有生成！！！";
                            MailHelper.SendMail(stepSubject,stepContent,mailReceiverPe);
                            continue;
                        }

                        
                        // lks 会有刻号的情况，会找不到AOI文件
                        int dashCount = testInfo.WF_ID.Split('-').Length - 1;
                        string AOIwfId = testInfo.WF_ID;
        
                        // 如果有两个或更多的 "-"，则进行截取操作
                        if (dashCount >= 2 && (testInfo.HEAD_LOT_ID!.Contains("LKS") || testInfo.HEAD_LOT_ID!.Contains("SYX")))
                        {
                            // 找到最后一个 "-" 的位置
                            int lastIndex = testInfo.WF_ID.LastIndexOf('-');
            
                            // 截取从开始到最后一个 "-" 之前的部分
                            AOIwfId = testInfo.WF_ID.Substring(0, lastIndex);
                        }
                       

                        #region 找aoi下面路径的文件
                        var possiblePaths = new List<string>
                        {
                            Path.Combine(aoiFilePath, aoiInfo.custCode!, aoiInfo.device!, "OQC", AOIwfId + ".txt"),
                            Path.Combine(aoiFilePath1, aoiInfo.custCode!, aoiInfo.device!, "OQC", AOIwfId + ".txt"),
                            Path.Combine(aoiFilePath, aoiInfo.custCode!, aoiInfo.device!, "OQC", testInfo.WF_LOT, AOIwfId + ".txt"),
                            Path.Combine(aoiFilePath1, aoiInfo.custCode!, aoiInfo.device!, "OQC", testInfo.WF_LOT, AOIwfId + ".txt"),
                            Path.Combine(aoiFilePath, aoiInfo.custCode!, aoiInfo.device!, "OQC", AOIwfId.Replace("-","_") + ".txt"),
                            Path.Combine(aoiFilePath1, aoiInfo.custCode!, aoiInfo.device!, "OQC", AOIwfId.Replace("-","_") + ".txt"),
                            Path.Combine(aoiFilePath, aoiInfo.custCode!, aoiInfo.device!, "OQC", testInfo.WF_LOT, AOIwfId.Replace("-","_") + ".txt"),
                            Path.Combine(aoiFilePath1, aoiInfo.custCode!, aoiInfo.device!, "OQC", testInfo.WF_LOT, AOIwfId.Replace("-","_") + ".txt"),
                            Path.Combine(aoiFilePath, aoiInfo.custCode!, aoiInfo.device!, "OQC", AOIwfId.Replace("-","") + ".smic"),
                            Path.Combine(aoiFilePath1, aoiInfo.custCode!, aoiInfo.device!, "OQC", AOIwfId.Replace("-","") + ".smic"),
                            

                        };

                        // 2. 筛选存在的文件
                        var existingFiles = possiblePaths
                            .Where(File.Exists)
                            .ToList();

                        // 3. 检查是否存在任何文件
                        if (!existingFiles.Any())
                        {
                            List<string> mailReceiver = StringUtils.GetMailReceiver();
                            string subject = "合图失败";
                            MailHelper.SendMail(subject, $"该{testInfo.HEAD_LOT_ID!}，{testInfo.CP_NO}，{testInfo.RP_NO}，{testInfo.WF_NO}片，找不到AOI文件", mailReceiver);
                            continue;
                        }

                        // 4. 查找最新文件
                        string aoiDetailFile = existingFiles
                            .OrderByDescending(File.GetLastWriteTime)
                            .First();
                        #endregion
                        
                        LogHelper.Info(aoiDetailFile);
                        if (!File.Exists(aoiDetailFile))
                        {
                            Console.WriteLine("File " + aoiDetailFile + "不存在");
                            LogHelper.Info("File " + aoiDetailFile + "不存在");
                            continue;
                        }


                        if (aoiInfo.custCode == "SMR" || aoiInfo.custCode == "SYX" || aoiInfo.custCode == "MXS")
                        {
                            LogHelper.Info("转化AOI文件");
                            ToolUtils.PreprocessingAoiTxt(aoiDetailFile,aoiInfo.custCode!);
                        }
                        
                        
                        LogHelper.Info($"目前正在测试{aoiInfo.custCode} -{aoiInfo.device}- {aoiInfo.row} - {aoiInfo.col}");
                        Console.WriteLine($"目前正在测试{aoiInfo.custCode} -{aoiInfo.device}- {aoiInfo.row} - {aoiInfo.col}");
                        
                        
                        
                        string AOIPath = aoiDetailFile;
                        
                        int _row = aoiInfo.row;
                        int _col = aoiInfo.col;
                        
                        int _arowFrom = aoiInfo.from_row;
                        int _arowTo = aoiInfo.to_row;
                        
                        int _acolFrom = aoiInfo.from_col;
                        int _acolTo = aoiInfo.to_col;
                         
                        // 读取的aoi的文件
                        string[,] arr_aoi = new string[_row + 1, _col + 1];
                        // 读取最后一个cp，最后一个rp的tmb文件
                        string[,] arr_tmb1 = new string[_row + 1, _col + 1];
                        
                        // 读取 tma的数据
                        string[,] arr_tma = new string[_row + 1, _col + 1];

                        if (aoiInfo.custCode == "LKS")
                        {
                            arr_tmb1 = new string[_col + 1, _row + 1];
                        }
                        
                        // 读取倒数第二个cp，最后一个rp的tmb文件
                        string[,] arr_tmb2 = new string[_row + 1, _col + 1];
                        // 存放tmb 和 aoi合图之后的文件
                        string[,] arr_result = new string[_row + 1, _col + 1];
                        // 读取 txt 的文件
                        string[,] arr_txt = new string[_row + 1, _col + 1];
                        string[,] arr_lks_txt = new string[_row + 1, _col + 1];
                        
                        // 用于存放 有哪些bin值
                        int[] arr_bins = new int[64 +1];
                        // 用于存放txt对应 的字符
                        string[] arr_bin_code = new string[600];
                        
                        
                        # region  建立map备份
                        string mapBackUpPath = Path.Combine(mapBakPath, aoiInfo.custCode!, aoiInfo.device! ,testInfo.WF_LOT);
                        if (!Directory.Exists(mapBackUpPath))
                        {
                            LogHelper.Info($"不存在该map目录: {mapBackUpPath}");
                            continue;
                        }
                        mapBackUpPath = Path.Combine(mapBackUpPath, "MERGE BACKUP");
                        if (!Directory.Exists(mapBackUpPath)) Directory.CreateDirectory(mapBackUpPath);
                        
                        
                        string[] searchPatternsMap = { "*.txt", "*.tmb","*.tma" };
                        string sourceMapPath = Path.Combine(mapBakPath, aoiInfo.custCode!, aoiInfo.device!, testInfo.WF_LOT,
                            testInfo.CP_NO!, testInfo.RP_NO!);
                        foreach (string pattern in searchPatternsMap)
                        {
                            foreach (string file in Directory.EnumerateFiles(sourceMapPath, pattern,
                                         SearchOption.TopDirectoryOnly))
                            {
                                
                                string destFile = Path.Combine(mapBackUpPath, Path.GetFileName(file));
                                if (!File.Exists(destFile))
                                {
                                    File.Copy(file,destFile,true);
                                }
                                
                                
                            }
                        }
                        #endregion
                        
                        # region 建立彩图备份
                        string colorMapBackUpPath = Path.Combine(colorMapBakPath, aoiInfo.custCode!, aoiInfo.device! ,testInfo.WF_LOT);
                        

                        colorMapBackUpPath = Path.Combine(colorMapBackUpPath, "MERGE BACKUP");
                        if (!Directory.Exists(colorMapBackUpPath)) Directory.CreateDirectory(colorMapBackUpPath);
                        
                        
                        string[] searchPatternsColorMap = { "*.xlsx", "*.xls" };
                        string sourceColorMapPath = Path.Combine(mapBakPath, aoiInfo.custCode!, aoiInfo.device!, testInfo.WF_LOT);
                        foreach (string pattern in searchPatternsColorMap)
                        {
                            foreach (string file in Directory.EnumerateFiles(sourceColorMapPath, pattern,
                                         SearchOption.TopDirectoryOnly))
                            {
                                
                                string destFile = Path.Combine(colorMapBackUpPath, Path.GetFileName(file));
                                if (!File.Exists(destFile))
                                {
                                    File.Copy(file, destFile, true);
                                }
                                
                        
                            }
                        }
                        
                        #endregion
                        
                        // 循环生成空的AOI数组
                        arr_aoi = StringUtils.GenerateNullAoiArr(arr_aoi);
                        
                        arr_tmb1 = StringUtils.GenerateNullTmbArr(arr_tmb1);
                        
                        arr_tma = StringUtils.GenerateNullTmbArr(arr_tma);
                        
                        
                        // 读取tmb文件
                        
                        WaferInfo newWaferInfo = new WaferInfo();
                        
                        // 读取tmb文件 
                        string outputTmbFile = Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,testInfo.CP_NO,testInfo.RP_NO,testInfo.WF_ID + ".tmb");
                        StringUtils.ReadTmbFile(outputTmbFile,tmbResult,arr_tmb1,newWaferInfo);
                        
                        // 读取tma文件
                        string outputTmaFile = Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,testInfo.CP_NO,testInfo.RP_NO,testInfo.WF_ID + ".tma");
                        StringUtils.ReadTmaFile(outputTmaFile,tmaResult,arr_tma);
                        
                        
                        // 读取AOI文件
                        
                        bool error = StringUtils.ReadAoiFile(AOIPath,_arowFrom,_arowTo,_acolFrom,_acolTo,arr_aoi);


                        if (error)
                        {
                            string aoimergeSubjectError = "合图有问题";
                            string aoimergeContentError = $@"该{testInfo.HEAD_LOT_ID!}，{testInfo.CP_NO}，{testInfo.RP_NO}，{testInfo.WF_NO}片，合图有问题,存在@字符！！！";
                            MailHelper.SendMail(aoimergeSubjectError,aoimergeContentError,mailReceiverPe);
                            continue;
                        }
                        
                        
                     
                        
                        int aoiFail = NormalMerge.ProcessCompareTmbAndAoi(aoiInfo.custCode!,_row,_col,arr_aoi,arr_result,arr_tmb1,testInfo);
                        
                        LogHelper.Info($"文件中Fail的个数：{aoiFail}");

                       
                        
                        // 生成 TMB 文件  TMC文件
                        StringUtils.GenerateTmbFile(tmbResult,_row,_col,arr_result,arr_bins,newWaferInfo,outputTmbFile,testInfo);
                        
                        //生成 TMA 文件
                        StringUtils.GenerateTmaFile(tmaResult, _row, _col, arr_result,newWaferInfo,
                            outputTmaFile, testInfo,arr_tma);
                        
                        
                        // 读取txt文件
                        if (aoiInfo.custCode != "HWG")
                        {
                            string txtSpecialWfId = wfNo.ToString("D3") + "." + testInfo.WF_ID;
                            string outputTxtFile =  Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,testInfo.CP_NO,testInfo.RP_NO, txtSpecialWfId + ".txt");

                            if (aoiInfo.custCode == "IMT" || aoiInfo.custCode == "MXS")
                            {
                                txtSpecialWfId =  testInfo.WF_ID;
                                outputTxtFile =  Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,testInfo.CP_NO,testInfo.RP_NO, txtSpecialWfId + ".txt");
                            }

                            if (aoiInfo.custCode == "ZJL")
                            {
                                txtSpecialWfId =  testInfo.WF_ID;
                                outputTxtFile =  Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,testInfo.CP_NO,testInfo.RP_NO, txtSpecialWfId + ".MAP");
                            }

                   
                            StringUtils.ReadTxtFile(outputTxtFile,txtResult,_row,_col,arr_txt);
                            StringUtils.GenerateTxtFile(outputTxtFile,txtResult, newWaferInfo,arr_bin_code,_row,_col,arr_txt,arr_result,arr_bins,testInfo,aoiInfo.custCode!);


                            if (aoiInfo.custCode == "LKS")
                            {
                                string outputLksTxtFile =  Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,testInfo.CP_NO,testInfo.RP_NO, txtSpecialWfId + "-B.txt");
                            
                                StringUtils.ReadLksTxtFile(outputLksTxtFile, lksTxtResult,_row,_col,arr_lks_txt);
                                
                                StringUtils.GenerateLksTxtFile(outputLksTxtFile,lksTxtResult, newWaferInfo,arr_bin_code,_row,_col,arr_lks_txt,arr_result,arr_bins,testInfo,aoiInfo.custCode!);
                            }
                            
                           
                        }
                        else
                        {
                            string txtSpecialWfId = testInfo.WF_ID + '-' + wfNo.ToString("D2");
                            string outputTxtFile =  Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,testInfo.CP_NO,testInfo.RP_NO, txtSpecialWfId + ".txt");
                            StringUtils.ReadHwgTxtFile("L:\\MapNewMMS\\HWG\\MARMOT_C\\A553752.1\\CP1\\RP1\\A553752.1-01.txt",txtResult,_row,_col,arr_txt);
                            StringUtils.GenerateHwgTxtFile(outputTxtFile,txtResult, newWaferInfo,arr_bin_code,_row,_col,arr_txt,arr_result,arr_bins,testInfo,aoiInfo.custCode!);
                        }
                       
                       
                        
                        
                        // 更新P_data_detail 的 数据
                        QueryUtils.UpdatePDataDetail(testInfo.SERIAL_NO, newWaferInfo.TotalTestDie.ToString(),
                            newWaferInfo.PassDie.ToString(), newWaferInfo.Yield, newWaferInfo.HBIN,testInfo.WF_NO.ToString()!);
                        
                        
                        // 先查询serial no 总和 的数据  并更新 P_data_head  表的数据
                        QueryUtils.QueryDataDetail(testInfo.SERIAL_NO);
                          
                        // 更新T_PROBE_DATA 的数据
                        QueryUtils.UpdateTProbaData(aoiInfo.device!, testInfo.WF_LOT, testInfo.WF_NO.ToString()!, aoiInfo.custCode!,
                            newWaferInfo.TotalTestDie.ToString(), newWaferInfo.PassDie.ToString(),aoiFail);
                        
                        // 更新报表和彩图的状态
                        QueryUtils.UpdateSummary(testInfo.HEAD_LOT_ID!,Convert.ToInt32(testInfo.WF_NO),testInfo.CP_NO,testInfo.RP_NO);
                        
                    
                        LogHelper.Info($"========================{outputTmbFile}更新完成====================================");
                        Console.WriteLine($"========================{outputTmbFile}更新完成====================================");
                        
                        
                        string aoimergeSubject = "合图完成";
                        string aoimergeContent = $@"该{testInfo.HEAD_LOT_ID!}，{testInfo.CP_NO}，{testInfo.RP_NO}，{testInfo.WF_NO}片，合图完成！！！";
                        MailHelper.SendMail(aoimergeSubject,aoimergeContent,mailReceiverPe);

                        if (QueryUtils.QueryDataDetailSum(testInfo.SERIAL_NO) != newWaferInfo.TotalTestDie)
                        {
                            string aoimergeSubjectError = "合图有问题";
                            string aoimergeContentError = $@"该{testInfo.HEAD_LOT_ID!}，{testInfo.CP_NO}，{testInfo.RP_NO}，{testInfo.WF_NO}片，合图有问题！！！";
                            MailHelper.SendMail(aoimergeSubjectError,aoimergeContentError,mailReceiverPe);
                        }
                        
                        
                        LogHelper.Info("===========普通合图结束===========");
                    }


                    // XYX复合芯片合图
                    foreach (TestInfo testInfo in testInfos)
                    {
                        
                        if(!testInfo.HEAD_LOT_ID!.Contains("XYX")) continue;
                        if(testInfo.CP_NO != "CP4") continue;
                        LogHelper.Info("===========复合芯片合图开始===========");
                        Console.WriteLine($"当前循环{testInfo.WF_LOT} -- {testInfo.WF_NO}--{testInfo.CP_NO}");
                        LogHelper.Info($"当前循环{testInfo.WF_LOT} -- {testInfo.WF_NO}--{testInfo.CP_NO}");
                        
                        testInfo.WF_LOT = Regex.Replace(testInfo.WF_LOT!, @"[\u202D\u200E\u200F\u202C\u202E]", "");
                        
                            
                        // 最后输出tmb的结果 CP4
                        StringBuilder tmbResultCp4 = new StringBuilder();
                        
                        // 最后输出tmb的结果 CP2
                        StringBuilder tmbResultCp2 = new StringBuilder();
                        
                        
                        
                        // 最后输出txt的结果
                        StringBuilder txtResult = new StringBuilder();
                        
                        
                        
                        
                        if (String.IsNullOrEmpty(testInfo.WF_ID) || String.IsNullOrEmpty(testInfo.WF_LOT) ||
                        String.IsNullOrEmpty(testInfo.CP_NO) || String.IsNullOrEmpty(testInfo.RP_NO) || 
                        String.IsNullOrEmpty(testInfo.SERIAL_NO))
                        {
                            continue;
                        }
                        
                        int wfNo = Convert.ToInt32(testInfo.WF_NO);
                        
                        LogHelper.Info($"目前正在测试{aoiInfo.custCode} -{aoiInfo.device}- {aoiInfo.row} - {aoiInfo.col}");
                        Console.WriteLine($"目前正在测试{aoiInfo.custCode} -{aoiInfo.device}- {aoiInfo.row} - {aoiInfo.col}");
                        bool isAoIink = QueryUtils.QueryIsAoIink(aoiInfo.device!,testInfo.WF_LOT,wfNo.ToString(),aoiInfo.custCode!);

                        if (isAoIink)
                        {
                            LogHelper.Info("复合芯片已经合过图");
                            Console.WriteLine("复合芯片已经合过图");
                            continue;
                        }
                        

                        
                        int _row = aoiInfo.row;
                        int _col = aoiInfo.col;
                        
                        
                        // 读取最后一个cp4，最后一个rp的tmb文件
                        string[,] arr_tmb1 = new string[_row + 1, _col + 1];
                        
                        // 读取cp2，最后一个rp的tmb文件
                        string[,] arr_tmb2 = new string[_row + 1, _col + 1];
                        // 存放cp4 和 cp2合图之后的文件
                        string[,] arr_result = new string[_row + 1, _col + 1];
                        // 读取 txt 的文件
                        string[,] arr_txt = new string[_row + 1, _col + 1];
                        
                        // 用于存放 有哪些bin值
                        int[] arr_bins = new int[64 +1];
                        // 用于存放txt对应 的字符
                        string[] arr_bin_code = new string[600];
                        
                        # region  建立map备份
                        string mapBackUpPath = Path.Combine(mapBakPath, aoiInfo.custCode!, aoiInfo.device! ,testInfo.WF_LOT);
                        if (!Directory.Exists(mapBackUpPath))
                        {
                            LogHelper.Info($"不存在该map目录: {mapBackUpPath}");
                            continue;
                        }
                        mapBackUpPath = Path.Combine(mapBackUpPath, "MERGE BACKUP");
                        if (!Directory.Exists(mapBackUpPath)) Directory.CreateDirectory(mapBackUpPath);
                        
                        
                        string[] searchPatternsMap = { "*.txt", "*.tmb","*.tma" };
                        string sourceMapPath = Path.Combine(mapBakPath, aoiInfo.custCode!, aoiInfo.device!, testInfo.WF_LOT,
                            testInfo.CP_NO!, testInfo.RP_NO!);
                        foreach (string pattern in searchPatternsMap)
                        {
                            foreach (string file in Directory.EnumerateFiles(sourceMapPath, pattern,
                                         SearchOption.TopDirectoryOnly))
                            {
                                
                                string destFile = Path.Combine(mapBackUpPath, Path.GetFileName(file));
                                if (!File.Exists(destFile))
                                {
                                    File.Copy(file,destFile,true);
                                }
                                
                                
                            }
                        }
                        #endregion
                        
                        
                        arr_tmb1 = StringUtils.GenerateNullTmbArr(arr_tmb1);
                        arr_tmb2 = StringUtils.GenerateNullTmbArr(arr_tmb2);
                        
                        
                        
                        // 读取tmb文件
                        
                        WaferInfo newWaferInfoCp4 = new WaferInfo();
                        
                        WaferInfo newWaferInfoCp2 = new WaferInfo();
                        
                        // 读取tmb文件 CP4的
                        string outputTmbFileCp4 = Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,testInfo.CP_NO,testInfo.RP_NO,testInfo.WF_ID + ".tmb");
                        StringUtils.ReadTmbFile(outputTmbFileCp4,tmbResultCp4,arr_tmb1,newWaferInfoCp4);
                        
                        // 读取tmb文件 CP4的
                        string outputTmbFileCp2 = Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,"CP2","FINAL",testInfo.WF_ID + ".tmb");
                        StringUtils.ReadTmbFile(outputTmbFileCp2,tmbResultCp2,arr_tmb2,newWaferInfoCp2);
                        
                        
                        string mergeTmbFileDir = Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,"MERGE-CP4-CP2");
                        
                        if (!Directory.Exists(mergeTmbFileDir)) Directory.CreateDirectory(mergeTmbFileDir);
                        
                        string mergeTmbFile = Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,"MERGE-CP4-CP2",testInfo.WF_ID + ".tmb");
                        StringUtils.MergeTmbCP4_CP2(_row,_col,arr_result,arr_tmb1,arr_tmb2);
                        
                        StringUtils.GenerateTmbFile(tmbResultCp4,_row,_col,arr_result,arr_bins,newWaferInfoCp4,mergeTmbFile,testInfo);
                        
                        string txtSpecialWfId = wfNo.ToString("D3") + "." + testInfo.WF_ID;
                        string outputTxtFile =  Path.Combine(mapBakPath,aoiInfo.custCode!,aoiInfo.device!,testInfo.WF_LOT,testInfo.CP_NO,testInfo.RP_NO, txtSpecialWfId + ".txt");
                        StringUtils.ReadTxtFile(outputTxtFile,txtResult,_row,_col,arr_txt);
                        
                        string mergeTxtFile = Path.Combine(mapBakPath, aoiInfo.custCode!, aoiInfo.device!,
                            testInfo.WF_LOT, "MERGE-CP4-CP2", txtSpecialWfId + ".txt");
                        
                        
                        StringUtils.GenerateTxtFile(mergeTxtFile,txtResult, newWaferInfoCp4,arr_bin_code,_row,_col,arr_txt,arr_result,arr_bins,testInfo,aoiInfo.custCode!);
                        
                        QueryUtils.UpdateTProbaDataXyx(aoiInfo.device!, testInfo.WF_LOT, testInfo.WF_NO.ToString()!, aoiInfo.custCode!);
                        List<string> mailReceiverPe = StringUtils.GetMailReceiver();   
                        string aoimergeSubject = "合图完成";
                        string aoimergeContent = $@"该{testInfo.HEAD_LOT_ID!}，{testInfo.CP_NO}，{testInfo.RP_NO}，{testInfo.WF_NO}片，复合芯片合图完成！！！";
                        MailHelper.SendMail(aoimergeSubject,aoimergeContent,mailReceiverPe);
                        LogHelper.Info("===========复合芯片合图结束===========");
                        
                    }
                    
                    
                    
                    // 这里是只要 dpat的
                    foreach (TestInfo testInfo in testInfos)
                    {
                        if (!testInfo.HEAD_LOT_ID!.Contains("ALG")) continue;
                        if (!testInfo.HEAD_LOT_ID!.Contains("SBW")) continue;
                        LogHelper.Info("===========DPAT合图开始===========");
                        LogHelper.Info($"当前循环{testInfo.WF_LOT} -- {testInfo.WF_NO}--{testInfo.CP_NO}");
                        
                        bool isAoIink = QueryUtils.QueryIsAoIink(aoiInfo.device!,testInfo.WF_LOT!,testInfo.WF_NO.ToString()!,aoiInfo.custCode!);

                        if (isAoIink)
                        {
                            LogHelper.Info("DPAT已经合过图");
                            Console.WriteLine("DPAT已经合过图");
                            continue;
                        }

                        if(testInfo.HEAD_LOT_ID!.Contains("ALG"))
                        {
                            using HttpClient client = new HttpClient();
                            string dpatApi =
                                $"http://10.20.5.21:8080/api/dpatAlg?lotID={testInfo.HEAD_LOT_ID}&wfLot={testInfo.WF_LOT}&Wfno={testInfo.WF_NO.ToString()}&cp={testInfo.CP_NO}&rp={testInfo.RP_NO}";

                            try
                            {
                                HttpResponseMessage response = await client.GetAsync(dpatApi);
                                LogHelper.Info(response.ToString());
                                response.EnsureSuccessStatusCode();
                                // 更新报表和彩图的状态
                                QueryUtils.UpdateSummaryAlg(testInfo.HEAD_LOT_ID!, Convert.ToInt32(testInfo.WF_NO), testInfo.CP_NO!, testInfo.RP_NO!);
                                // 更新T_PROBE_DATA 的数据
                                QueryUtils.UpdateTProbaDataAlg(aoiInfo.device!, testInfo.WF_LOT!, testInfo.WF_NO.ToString()!, aoiInfo.custCode!);
                                LogHelper.Info($"========================{testInfo.HEAD_LOT_ID},{testInfo.WF_ID}DPAT更新完成====================================");
                                Console.WriteLine($"========================{testInfo.HEAD_LOT_ID},{testInfo.WF_ID}DPAT更新完成====================================");

                            }
                            catch (HttpRequestException e)
                            {

                                List<string> mailReceiver = StringUtils.GetMailReceiver();
                                string subject = "dpat出现错误";
                                LogHelper.Error(subject);
                                MailHelper.SendMail(subject, e.Message, mailReceiver);
                            }
                        }


                        if(testInfo.HEAD_LOT_ID!.Contains("SBW"))
                        {
                           
                            LogHelper.Info($"当前循环{testInfo.WF_LOT} -- {testInfo.WF_NO}--{testInfo.CP_NO}");
                            using HttpClient client = new HttpClient();
                            string dpatApi =
                                $"http://10.0.3.213:9110/api/StdfRetrieve/StdfDpatAndInk_SBW?lotID={testInfo.HEAD_LOT_ID}&Wfno={testInfo.WF_NO}";

                            try
                            {
                                HttpResponseMessage response = await client.GetAsync(dpatApi);
                                LogHelper.Info(dpatApi);
                                response.EnsureSuccessStatusCode();

                                QueryUtils.UpdateSummary(testInfo.HEAD_LOT_ID!, Convert.ToInt32(testInfo.WF_NO), testInfo.CP_NO!, testInfo.RP_NO!);
                            }
                            catch (HttpRequestException e)
                            {

                                List<string> mailReceiver = StringUtils.GetMailReceiver();
                                string subject = "dpat出现错误";
                                LogHelper.Error(subject);
                                MailHelper.SendMail(subject, e.Message, mailReceiver);
                            }

                        }

                        LogHelper.Info("===========DPAT合图结束===========");
                    }
                    
                    
                   
                    
                    LogHelper.Info("===========导入SUMMARY合图开始===========");
                    AoiSummary.Run(aoiInfo,aoiFilePath);
                    AoiSummary.Run(aoiInfo,aoiFilePath1);
                    
                    LogHelper.Info("===========导入SUMMARY合图结束===========");
                }
                
                
                
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                List<string> mailReceiver = StringUtils.GetMailReceiver();
                MailHelper.SendMail("合图报错", ex.Message, mailReceiver);
            }
        }
    }
}
